package com.ruoyi.message.general.service;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import com.ruoyi.message.general.properties.JtdProperties;
import com.ruoyi.message.general.util.OkHttp3Util;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MultipartBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 聚通达 服务
 */
@Service
@Slf4j
public class JtdService {
    private static final Map<String, String> errorMap = new HashMap<>();

    @Autowired
    private JtdProperties jtd;

    static {
        errorMap.put("-2", "缺少参数");
        errorMap.put("-3", "账号信息有误");
        errorMap.put("-4", "余额不足");
        errorMap.put("-5", "参数格式不正确");
        errorMap.put("-6", "内容太长");
        errorMap.put("-8", "扩展长度不正确");
        errorMap.put("-9", "Ip地址未授权");
        errorMap.put("-990", "未知异常");
    }

    public  boolean sendSms(String phone, String context) {
        MultipartBody multipartBody = new MultipartBody.Builder()
                .addFormDataPart("uid", jtd.getUid())
                .addFormDataPart("password", SecureUtil.md5(jtd.getPassword()).toUpperCase())
                .addFormDataPart("mobile", phone)
                .addFormDataPart("content", Base64.encodeStr(context.getBytes(StandardCharsets.UTF_8), false, false))
                .addFormDataPart("encode", "utf8")
                .addFormDataPart("encodeType", "base64")
                .build();
        Response response = OkHttp3Util.send("https://sms3api.jvtd.cn/jtdsms/smsSend", null, OkHttp3Util.POST, multipartBody);
        try {
            String result = response.body().string();
            for (String code : errorMap.keySet()) {
                if (result.equals(code)) {
                    return false;
                }
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return false;
    }
}
